package cn.cmvideo.xworld.adapter;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import cn.cmvideo.xworld.activity.DetailActivity;
import cn.cmvideo.xworld.model.Content;
import cn.cmvideo.xworld.util.MyImageLoader;

public class ViewPagerAdapter extends PagerAdapter {
	private List<View> views;
	private Context context;
	private MyImageLoader imageLoader = null;

	public ViewPagerAdapter(Context context, List<View> views) {
		this.context = context;
		this.views = views;
		imageLoader = new MyImageLoader(context);
	}

	@Override
	public int getCount() {
		return views.size();
	}

	@Override
	public void startUpdate(View container) {
	}

	@Override
	public Object instantiateItem(View container, final int position) {
		ImageView iv = (ImageView) views.get(position);
		Content content = (Content) iv.getTag();
		iv.setScaleType(ScaleType.FIT_XY);
		((ViewPager) container).addView(iv, 0);
		imageLoader.loadImage(content.src, iv);
		iv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Content content = (Content) v.getTag();
				String[] params = (content.link).split("\\?")[1].split("&");
				String param = "";
				param = "contentId=" + params[1].split("=")[1] + ";nodeId="
						+ params[0].split("=")[1] + ";objType="
						+ params[2].split("=")[1];
				Intent intent = new Intent();
				intent.setClass(context, DetailActivity.class);
				intent.putExtra("param", param);
				context.startActivity(intent);
			}
		});
		return views.get(position);
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return (arg0 == arg1);
	}

	@Override
	public Parcelable saveState() {
		return super.saveState();
	}

	@Override
	public void finishUpdate(View container) {
	}

	@Override
	public void restoreState(Parcelable state, ClassLoader loader) {
		super.restoreState(state, loader);
	}

	@Override
	public void destroyItem(View container, int position, Object object) {
		((ViewPager) container).removeView(views.get(position));
	}

}
